import type { App } from 'vue'
import { createI18n } from 'vue-i18n'
import { computed } from 'vue'
import en from 'element-plus/es/locale/lang/en'
import zhCN from 'element-plus/es/locale/lang/zh-cn'

type I18nGlobalTranslation = {
  (key: string): string
  (key: string, locale: string): string
  (key: string, locale: string, list: unknown[]): string
  (key: string, locale: string, named: Record<string, unknown>): string
  (key: string, list: unknown[]): string
  (key: string, named: Record<string, unknown>): string
}

type I18nTranslationRestParameters = [string, any]
let globalMessages = {}
// Default messages for component library
const defaultMessages = {
  'zh-CN': {
    ...zhCN,
   
  },
  'en': {
    ...en,
   
  }
}

// Global i18n instance for the component library
let globalI18n: any = null

const getKey = (namespace: string | undefined, key: string) => {
  if (!namespace) {
    return key
  }
  if (key.startsWith(namespace)) {
    return key
  }
  return `${namespace}.${key}`
}

export const useI18n = (
  namespace?: string
): {
  t: I18nGlobalTranslation
} => {
  const normalFn = {
    t: (key: string) => {
      return getKey(namespace, key)
    }
  }

  if (!globalI18n) {
    return normalFn
  }

  const { t: globalT } = globalI18n.global

  // Create a reactive translation function
  const tFn: I18nGlobalTranslation = (key: string, ...arg: any[]) => {
    if (!key) return ''
    if (!key.includes('.') && !namespace) return key
    
    // Use computed to make it reactive
    return computed(() => {
      //@ts-ignore
      return globalT(getKey(namespace, key), ...(arg as I18nTranslationRestParameters))
    }).value
  }
  
  return {
    t: tFn
  }
}

// Initialize i18n instance
export const createI18nForLib = (locale: LocaleType = 'zh-CN', messages?: any) => {
  globalMessages={...globalMessages,...messages}
  const mergedMessages =   Object.keys(defaultMessages).reduce((acc, key) => {
      acc[key] = { ...(defaultMessages as any)[key], ...(globalMessages as any)[key] }
      return acc
    }, {} as any)

  globalI18n = createI18n({
    legacy: false,
    locale,
    fallbackLocale: 'zh-CN',
    messages: mergedMessages,
    silentTranslationWarn: false, 
  })
  console.log(messages,mergedMessages)
  return globalI18n
}

// Install function for Vue app
export const setupI18n = (app: App, options?: { locale?: LocaleType; messages?: any }) => {
  const i18n = createI18nForLib(options?.locale, options?.messages)
  app.use(i18n)
  return i18n
}

export const t = (key: string) => {
  if (!globalI18n) return key
  console.log(globalI18n.global.t(key))
  return globalI18n.global.t(key)
}
